package Demo1;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-07-13
 * Time: 15:30
 */
public class MyStack {
    private int[] array;
    private int useSize;
    public static final int CONTAINER_SIZE = 10;

    public MyStack() {
        this.array = new int[CONTAINER_SIZE];
    }

    //压栈
    public void push(int data){
        //检测是否需要扩容
        if(array.length == useSize){
            array = Arrays.copyOf(array,2 * array.length);
        }

        array[useSize++] = data;
    }
    //出栈
    public int pop(){
        try{
            checkEmpty();
            return array[--useSize];
        }catch(arrayEmpty e){
            e.printStackTrace();
        }
        return -1;
    }
    //获取栈顶元素
    public int peek(){
        try{
            checkEmpty();
            return array[useSize - 1];
        }catch(arrayEmpty e){
            e.printStackTrace();
        }
        return -1;
    }

    private void checkEmpty() throws arrayEmpty{
        if(isEmpty()){
            throw new arrayEmpty("栈为空");
        }
    }
    //判断栈是否为空
    public boolean isEmpty(){
        return useSize == 0;
    }
    //获取栈中有效元素个数
    public int size(){
       return this.useSize;
    }
}
